package com.jizi.machine.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jizi.machine.service.MachineService;
import com.jizi.machine.vo.RobotVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.assertj.core.util.Strings;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.List;

/**
 * description :
 * author :kang
 * create :2021-11-24 21:16:00
 */
@Service
public class MachineServiceImpl implements MachineService {

    @Override
    public void run(RobotVo vo) throws IOException {
        List<String> memberList = vo.getMemberList();
        String jsonData = "";
        String mobileList = "";
        String strMember = "";
        if (vo.getMsgType().equals("text")) {
            if (!Strings.isNullOrEmpty(vo.getMobileList())) {
                mobileList = vo.getMobileList();
            } else {
                mobileList = "";
            }
            for (int i = 0; i < memberList.size(); i++) {
                if (i == memberList.size() - 1) {
                    strMember += "\"" + memberList.get(i) + "\"";
                } else {
                    strMember += "\"" + memberList.get(i) + "\"" + ",";
                }
            }
            String[] members = new String[memberList.size()];
            for (int i = 0; i < memberList.size(); i++) {
                members[i] = memberList.get(i);
            }
            jsonData = "{\n" +
                    "\t\"msgtype\": \"" + vo.getMsgType() + "\",\n" +
                    "    \"text\": {\n" +
                    "        \"content\": \"" + vo.getContent() + "\",\n" +
                    "        \"mentioned_list\":[" + strMember + "],\n" +
                    "        \"mentioned_mobile_list\":[\"" + mobileList + "\"]\n" +
                    "    }\n" +
                    "}";

        } else if (vo.getMsgType().equals("image")) {
            String download = download(vo.getSavePath(), "C:\\Users\\q'q\\Pictures");
            vo.setSavePath(download == null ? vo.getSavePath() : download);

            //图片base64加密的值
            vo.setImageBase64Value(getImageStr(vo.getSavePath()));
            //图片md5加密的值
            vo.setImageMd5Value(DigestUtils.md5Hex(new FileInputStream(vo.getSavePath())));
            jsonData = "{\n" +
                    "    \"msgtype\": \"" + vo.getMsgType() + "\",\n" +
                    "    \"image\": {\n" +
                    "        \"base64\": \"" + vo.getImageBase64Value() + "\",\n" +
                    "        \"md5\": \"" + vo.getImageMd5Value() + "\"\n" +
                    "    }\n" +
                    "}";
        } else if (vo.getMsgType().equals("news")) {
            //图片+文字消息
            vo.setTitle(!Strings.isNullOrEmpty(vo.getTitle()) ? vo.getTitle() : "");
            jsonData = "{\n" +
                    "    \"msgtype\": \"" + vo.getMsgType() + "\",\n" +
                    "    \"news\": {\n" +
                    "       \"articles\" : [\n" +
                    "           {\n" +
                    "               \"title\" : \"" + vo.getTitle() + "\",\n" +
                    "               \"description\" : \"" + vo.getDescription() + "\",\n" +
                    "               \"url\" : \"" + vo.getUrl() + "\",\n" +
                    "               \"picurl\" : \"" + vo.getImageUrl() + "\"\n" +
                    "           }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
        }
        send(vo.getWebhookAddress(), jsonData);
    }

    /**
     * 根据图片地址转换为base64编码字符串
     *
     * @param imgFile
     * @return
     */
    public static String getImageStr(String imgFile) {
        //要想发送图片内容需要将图片加密转化成base64编码
        InputStream inputStream = null;
        byte[] data = null;
        try {

            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片加密
        Base64.Encoder er = Base64.getEncoder();
        return er.encodeToString(data);
    }

    public static JSONObject send(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        JSONObject jsonObject = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流（设置请求编码为UTF-8）
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取请求返回数据（设置返回数据编码为UTF-8）
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static String download(String urlList, String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            // 打开连接
            URLConnection con = url.openConnection();
            //设置请求超时为5s
            con.setConnectTimeout(5 * 1000);
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File sf = new File(path);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            //保存路径和文件名，图片类型
            String patht = sf.getPath() + "\\" + System.currentTimeMillis() + ".jpg";
            OutputStream os = new FileOutputStream(patht);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                //开始保存
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
            return patht;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
